<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>

      <div  v-if="!searchGroup" style="height: 40px">
<!--        先取消，有需要再打开-->
<!--        <el-form-item label="报表类型">-->
<!--          <el-select v-model="queryParams.tableType" placeholder="请选择" size="small"-->
<!--                     style="position: relative;top: 2px;width: 120px" @change="setTableType">-->
<!--            <el-option :value="1" label="按日"/>-->
<!--            <el-option :value="2" label="按月"/>-->
<!--            <el-option :value="3" label="按年"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="时间段"  >
          <el-date-picker v-if="queryParams.tableType == 1"
            v-model="dateRangeTime"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="left"
            size="small"
            style="position: relative;top: 2px;width: 250px"
            @change="handleQuery">
          </el-date-picker>
          <el-date-picker v-if="queryParams.tableType == 2"
                          v-model="dateRangeTime"
                          type="monthrange"
                          value-format="yyyy-MM"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          align="left"
                          size="small"
                          style="position: relative;top: 2px;width: 250px"
                          @change="setDateRangeTime">
          </el-date-picker>
          <yearPicker v-if="queryParams.tableType == 3"
            v-model="yearRange"
            start-placeholder="开始年份"
            end-placeholder="结束年份"
            @change="val=>setYearRange(val)"/>
        </el-form-item>
<!--        <el-form-item label="钢种" prop="steelGrade">-->
<!--          <el-input v-model="queryParams.steelGrade" placeholder="请输入钢种"/>-->
<!--        </el-form-item>-->
      </div>
      <div v-if="searchGroup" >
        <el-form-item label="时间段" >
          <el-date-picker
            v-model="dateRangeTeam"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="left"
            size="small"
            style="position: relative;top: 2px;width: 250px"
            @change="handleQuery">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="班次" prop="classesName" v-if="searchGroup">
          <el-select v-model="queryParams.classesName" placeholder="请选择" clearable size="small"
                     style="position: relative;top: 2px;width: 100px" @change="handleQuery">
            <el-option
              v-for="classes in classesList"
              :key="classes.classesId"
              :label="classes.classesName"
              :value="classes.classesName"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="班组" prop="teamName" v-if="searchGroup">-->
<!--          <el-select v-model="queryParams.teamName" placeholder="请选择" clearable size="small"-->
<!--                     style="position: relative;top: 2px;width: 100px" @change="handleQuery">-->
<!--            <el-option-->
<!--              v-for="team in teamList"-->
<!--              :key="team.teamId"-->
<!--              :label="team.teamName"-->
<!--              :value="team.teamName"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="钢种" prop="steelGrade">-->
<!--          <el-input v-model="queryParams.steelGrade" placeholder="请输入钢种"/>-->
<!--        </el-form-item>-->
      </div>
      <div style="height: 40px">
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh-right" size="mini" @click="rebuild">重置</el-button>
<!--          <el-button type="primary" icon="el-icon-download" size="mini" @click="handleDownload">导出</el-button>-->
          <el-checkbox v-model="searchGroup" style="margin-left: 10px" @change="handleQuery">班次查询</el-checkbox>
        </el-form-item>
      </div>
    </el-form>

    <el-table :data="list" class="tableStyle"  highlight-current-row  :height="tableHeight">
      <el-table-column label="日期" align="center"  prop="rawDate" :formatter="dateFormat" >
      </el-table-column>
      <el-table-column label="物料名称" align="center" prop="matterName"/>
      <el-table-column label="班次" align="center" prop="classesName"  v-if="searchGroup"/>
      <el-table-column label="班组" align="center" prop="teamName" v-if="searchGroup"/>


      <el-table-column label="消耗量" align="center" prop="consumption"/>
      <el-table-column label="消耗成本" align="center" prop="consumptionCost"/>

<!--      <el-table-column label="创建时间" align="center" prop="createTime" />-->
<!--      <el-table-column label="修改时间" align="center" prop="updateTime"/>-->
<!--      <el-table-column label="创建人" align="center" prop="createBy" />-->
<!--      <el-table-column label="修改人" align="center" prop="updateBy"/>-->
<!--      <el-table-column label="备注" align="center" prop="remark"/>-->
<!--      <el-table-column label="钢水量(t)" align="center" prop="steelQuanity" />-->
<!--      <el-table-column label="覆盖剂(kg)" align="center" prop="coveringAgent" />-->


    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div v-if="searchGroup">
      <table class="operate-table" style="margin-left: 1px;margin-right: 0px;width: 99.7%;border-radius: 0.5em;border-collapse: collapse;padding: 0;">
        <caption style="font-weight: bold;font-size: 20px;background-color: #bfefff;line-height: 35px;">当天料种报表 </caption>
        <tbody >
        <tr>
          <td style="background-color:  #dcdcdc;font-weight:bold;"></td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">1</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">2</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">3</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">4</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">5</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">6</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">7</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">8</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">9</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">10</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">11</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">12</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">13</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">14</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">15</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">16</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">17</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">18</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">19</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">20</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">21</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">22</td>
          <td style="background-color:  #dcdcdc;font-weight:bold;">累计</td>
        </tr>
        <tr >
          <td >名称</td>
          <td v-for="(value, key) in curMap.values()"
              :key="key"
          style="border: 1px solid black;border-color: #ffa200;">{{value.name}}</td>

          <td v-for="(value, key) in nullList"
              :key="key"
              style="border: 1px solid black;border-color: #ffa200;">{{value.name}}</td>
          <td></td>
        </tr>
        <tr >
          <td >夜班</td>
          <td v-for="(value, key) in curMap.values()"
              :key="key" >{{value.night}}</td>

          <td v-for="(value, key) in nullList"
              :key="key" >{{value.night}}</td>
          <td>{{nightTotal}}</td>
        </tr>
        <tr>
          <td >白班</td>
          <td v-for="(value, key) in curMap.values()"
              :key="key" >{{value.day}}</td>
          <td v-for="(value, key) in nullList"
              :key="key" >{{value.day}}</td>
          <td>{{dayTotal}}</td>
        </tr>
        <tr >
          <td >中班</td>
          <td v-for="(value, key) in curMap.values()"
              :key="key" >{{value.mid}}</td>
          <td v-for="(value, key) in nullList"
              :key="key" >{{value.mid}}</td>
          <td>{{midTotal}}</td>

        </tr>


        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
// import {exportSmeltingGroup, listGroup, pageGroup} from '@/api/app/smelt/group'
import{listConsumption, pageConsumption} from '@/api/app/productionMat/consumption'
import {listClasses} from '@/api/app/group/classes'
import {listTeam} from '@/api/app/group/team'
import moment from "moment/moment";
import yearPicker  from "./YearRangePicker.vue";

export default {
  components: {
    yearPicker
  },
  data() {
    return {
      total: 0,
      tableHeight:this.tableHeight,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        classesName: null,
        groupName: null,
        year: this.moment().format('YYYY'),
        month: this.moment().format('M'),
        day: null,//this.moment().format('YYYY-MM-DD'),
        date:null,
        tableType:1,//报表类型，默认日报表
        dateType: 1,
        steelGrade:null,
        // lfNo: 1
      },
      dateRangeTeam: [this.moment().format('YYYY-MM-01'), this.moment().format('YYYY-MM-DD')],
      dateRangeTime: [,],
      yearRange:['',''],
      searchGroup: false,
      //searchType: 1,
      classesList: [],
      teamList: [],
      // 表格数据
      list: [],
      mapMaxSize:22,
      curMap:new Map(),
      nullList:[],
      nightTotal:0.0,//夜班累计
      dayTotal:0.0,//白班累计
      midTotal:0.0,//中班累计
      materialItem:{
        name:'',
        night:null,
        day:null,
        mid:null
      },
    }
  },

  computed: {
    yearOptions() {
      let res = []
      for (let i = 2022; i <= this.moment().format('YYYY'); i++) {
        res.push(i)
      }
      return res
    }
  },
  async created() {
    // await getConfigKey('prodCode').then(res => {
    //   this.queryParams.prodCode = res.msg
    // })
    this.getClassesList()
    this.getTeamList()
    this.getList()
  },
  mounted() {
    this.tableHeight = (window.innerHeight - 270)  + "px"; //260即表格之外的固定高度

    window.onresize = () => {
      return (() => {
        this.tableHeight = (window.innerHeight -270)  + "px";

      })();
    };
  },
  methods: {
    //表头样式，
     renderHeader(h, { column, $index }) {
      let columnArr = column.label.split("||");//此处换行标志
      if (columnArr.length >= 2) {
        let divArr = [];
        columnArr.map((item) => {
          divArr.push(h("div", { style: "text-align: center " }, item));
        });
        return h("div", {}, divArr);
      }
      return h("div", {}, column.label);
    },

getClassesList() {
      listClasses({}).then(res => {
        this.classesList = res.data.rows
      })
    },
    getTeamList() {
      listTeam({}).then(res => {
        this.teamList = res.data.rows
      })
    },
    getCurrDate(){
      var date = new Date();
      var year = date.getFullYear();  // 年份
      var month = date.getMonth() + 1;  // 月份，返回值为0-11，所以需要加1
      var day = date.getDate();  // 日期

// 对月份和日期进行补零
      month = month < 10 ? '0' + month : month.toString();
      day = day < 10 ? '0' + day : day.toString();

      var currentDate = year +"-"+ month+"-" + day+" 00:00:00";
      console.log("current Date is "+currentDate);
      return currentDate;
    },
    /** 查询班次列表 */
    getList() {
      this.loading = true
      this.queryParams.beginDate = null
      this.queryParams.endDate = null
      // debugger
      if(!this.searchGroup){
        this.tableHeight = (window.innerHeight - 270)  + "px";
        if (this.dateRangeTime) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTime[0]
          this.queryParams.endDate = this.dateRangeTime[1]
          this.queryParams.dateType = 1
          console.log("时间"+this.queryParams.endDate)
        }
        pageConsumption(this.queryParams).then(res => {
          this.list = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      }else {
        let _this = this;
        this.tableHeight = (window.innerHeight - 470)  + "px";
        if (this.dateRangeTeam) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTeam[0]
          this.queryParams.endDate = this.dateRangeTeam[1]
          this.queryParams.dateType = 0
          console.log("班组"+this.queryParams.beginDate)

        }
        pageConsumption(this.queryParams).then(res => {
          this.list = res.data.rows
          this.total = res.data.total
          this.loading = false
          {
            //归0
            _this.nightTotal = 0.0
            _this.dayTotal = 0.0
            _this.midTotal = 0.0
            _this.curMap.clear();
            //表格赋值
            var filterList = this.list.filter(item=>item.rawDate === this.getCurrDate())
            // console.log("this.filterList "+filterList)
            for (const element of filterList){
                var matName = element.matterName
                if(_this.curMap.size!= 0 && _this.curMap.has(matName)){

                  item = _this.curMap.get(matName)
                  if(element.classesName === "夜班"){
                    item.night = element.consumption
                    _this.nightTotal += element.consumption

                  }else if(element.classesName === "白班"){
                    item.day = element.consumption
                    _this.dayTotal += element.consumption
                  }else if(element.classesName === "中班"){
                    item.mid = element.consumption
                    _this.midTotal += element.consumption
                  }
                }else
                {
                  if(element.classesName === "夜班"){
                    var item={
                      name:matName,
                      night:element.consumption,
                      day:0.0,
                      mid:0.0
                    }
                    _this.curMap.set(element.matterName, item);
                    _this.nightTotal += element.consumption

                  }else if(element.classesName === "白班"){
                    var item={
                      name:matName,
                      night:0.0,
                      day:element.consumption,
                      mid:0.0
                    }
                    _this.curMap.set(element.matterName, item);
                    _this.dayTotal += element.consumption
                  }else if(element.classesName === "中班"){
                    var item={
                      name:matName,
                      night:0.0,
                      day:0.0,
                      mid:element.consumption
                    }
                    _this.curMap.set(matName, item);
                    _this.midTotal += element.consumption
                  }


                }
            }

            this.nullList = [];
            var num = _this.curMap.size;
            for(let i = 0;i<this.mapMaxSize - num;i++)
            {
              var item={
                name:'',
                night:0.0,
                day:0.0,
                mid:0.0
              }
              this.nullList.push(item);
            }
          console.log("this curMap is "+this.curMap +" "+_this.curMap)
          }
        })
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      // debugger
      this.queryParams.pageNum = 1
      // this.setDateRangeTime()
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDownload() {
// debugger
      //查询时间统计表
      this.queryParams.beginDate = null
      this.queryParams.endDate = null
      // debugger
      if(!this.searchGroup){
        if (this.dateRangeTime) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTime[0]
          this.queryParams.endDate = this.dateRangeTime[1]
          console.log("时间"+this.queryParams.endDate)
        }
        if(this.queryParams.tableType ===1)
        {
          exportSmeltingDay(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }else if(this.queryParams.tableType===2)
        {
          exportSmeltingMonth(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }else if(this.queryParams.tableType===3)
        {
          exportSmeltingYear(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }


      }else {
        if (this.dateRangeTeam) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTeam[0]
          this.queryParams.endDate = this.dateRangeTeam[1]
          console.log("班组"+this.queryParams.beginDate)

        }
        exportSmeltingGroup(this.queryParams).then(res => {
          this.download(res.msg)
        })
      }

    },
    rebuild() {


      if (!this.searchGroup) {
        this.queryParams.tableType = 1
        this.queryParams.dateType = 1
        this.queryParams.beginDate = null
        this.queryParams.endDate = null
        this.queryParams.steelGrade = null
        this.dateRangeTime = [,]
      } else {
        this.queryParams.dateType = 0
        this.queryParams.classesName = null
        this.queryParams.groupName = null
        this.queryParams.steelGrade = null
        this.dateRangeTeam = [,]

      }
      this.getList();
    },
    setTableType(){
      this.dateRangeTime=[,];
      this.handleQuery()
    },
    setYearRange(yearValue){
       debugger

      this.yearRange = yearValue;
       if(this.yearRange[0] !== '')
       {
         this.dateRangeTime[0] = `${yearValue[0]}-01-01 00:00:00`;
       }else{
         this.dateRangeTime[0]=null;
       }
      if(this.yearRange[1] !== '')
      {
        this.dateRangeTime[1] = `${yearValue[1]}-12-31 23:59:59`;
      }else{
        this.dateRangeTime[1]=null;
      }

        // if(this.yearRange !== null)
        // {
        //   this.dateRangeTime = [`${yearValue[0]}-01-01 00:00:00`, `${yearValue[1]}-12-31 23:59:59`]
        //   console.log(this.dateRangeTime)
        // }else{
        //   this.dateRangeTime=[,];
        // }
        this.handleQuery();

    },
    setDateRangeTime() {
      // debugger

      if (this.queryParams.tableType === 2) {
        if(this.dateRangeTime)
        {
          this.dateRangeTime = [`${this.dateRangeTime[0]}-01 00:00:00`, `${this.dateRangeTime[1]}-01 00:00:00`]
        }

        console.log(this.dateRangeTime)
      }
       this.handleQuery();
      // let year = this.queryParams.yearTime
      // let month = this.queryParams.monthTime
      // if (this.queryParams.tableType == 3) {
      //   this.dateRangeTime = [`${year}-01-01 00:00:00`, `${year}-12-31 23:59:59`]
      //   console.log(this.dateRangeTime)
      // }
      // if (this.queryParams.tableType == 2) {
      //   let startMoment = this.moment([year, month - 1, 1])
      //   this.dateRangeTime = [startMoment.format('YYYY-MM-DD HH:mm:ss'), startMoment.endOf('month').format('YYYY-MM-DD HH:mm:ss')]
      //   console.log(this.dateRangeTime)
      // }
      // if (this.queryParams.tableType == 1) {
      //   let s=this.dateRangeTime[0]
      //   let e=this.dateRangeTime[1]
      //   e.setHours(e.getHours()+23)
      //   e.setMinutes(e.getMinutes()+59)
      //   e.setSeconds(e.getSeconds()+59)
      //   this.dateRangeTime = [s, e]
      //   console.log(this.dateRangeTime)
      // }

    },
    setDateRange() {
      let year = this.queryParams.year
      let month = this.queryParams.month
      let day = this.queryParams.day
      if (this.searchType == 2) {
        this.dateRangeTeam = [`${year}-01-01`, `${year}-12-31`]
        console.log(this.dateRangeTime)
      }
      if (this.searchType == 3) {
        let startMoment = this.moment([year, month - 1, 1])
        this.dateRangeTeam = [startMoment.format('YYYY-MM-DD'), startMoment.endOf('month').format('YYYY-MM-DD')]
      }
      if (this.searchType == 4) {
        this.dateRangeTeam = [day, day]
      }
    },
    dateFormat(row){

      let date = row.rawDate
      return moment(date).format('YYYY-MM-DD')
      // if(this.searchGroup)
      // {
      //   return moment(date).format('YYYY-MM-DD')
      // }
      // if(row.tableType==1){
      //   return moment(date).format('YYYY-MM-DD')
      // }else if(row.tableType==2){
      //   return moment(date).format('YYYY-MM')
      // }else if(row.tableType==3){
      //   return moment(date).format('YYYY')
      // }else {
      //   return date
      // }

    },
  }
}
</script>
<style lang="scss" scoped>
.tableStyle{
  ::v-deep th{
    text-align: center;
    //padding: 0px 0;
    //font-size: xx-small;
    //background-color:  #dcdcdc;
  }
  ::v-deep td{
    //padding: 0px 0;
    text-align: center;
    //font-size: xx-small
  }
}
/* 表头内容如何居中 */
::v-deep .el-table th.el-table__cell>.cell {
  padding: 0 0;

}

/* 表格内容如何居中 */
::v-deep .el-table td.el-table__cell div {
  text-align: center;
  padding: 0 0;
}
::v-deep.operate-table td {
  font-size: 14px;
  text-align: center;

  font-family: 宋体, Arial;
  border: 1px solid black;
  border-color: #CFCFCF;
  color: #000000;
  padding: 3px ;
  ::v-deep.alt {
    background: #F5FAFA;
    color: #797268;
  }

}
::v-deep.operate-table tr {
  height: 30px;

}

::v-deep.operate-table  tbody {
  margin:0  auto;
  width: 100%;
}
</style>
